package com.jeeplus.modules.web.wx;

import com.alibaba.druid.util.StringUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.monitor.model.Message;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.monitor.utils.Business;
import com.jeeplus.modules.monitor.utils.FileBean;
import com.jeeplus.modules.monitor.utils.MoneyTest;
import com.jeeplus.modules.web.entity.*;
import com.jeeplus.modules.web.entity.wx.YsUser;
import com.jeeplus.modules.web.mapper.*;
import com.jeeplus.modules.web.service.WxUserWalletDetailsService;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import com.vdurmont.emoji.EmojiParser;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by rongj on 2017/8/6.
 */
@Controller
@RequestMapping(value = "/wx/user_info")
public class YjUserController extends BaseController {
    @Autowired
    WxUserMapper wxUserMapper;
    @Autowired
    WxUserWalletMapper wxUserWalletMapper;
    @Autowired
    WxMoneyMapper wxMoneyMapper;
    @Autowired
    WxUserCouponMapper wxUserCouponMapper;
    @Autowired
    WxCouponTypeMapper wxCouponTypeMapper;
    @Autowired
    WxAgentsMapper wxAgentsMapper;
    @Autowired
    WxAgentsEquipmentMapper wxAgentsEquipmentMapper;
    @Autowired
    private WxUserWalletDetailsService wxUserWalletDetailsService;
    private static String appid =Global.getConfig("appId");// 应用ID
    private static String appsecret = Global.getConfig("appSecret");// 应用密钥

    private static String salesmanAppId = Global.getConfig("salesmanAppId"); //业务员小程序appid
    private static String salesmanAppSecret = Global.getConfig("salesmanAppSecret"); //业务员小程序appSecret

    /***
     * 登陆
     *
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody

    public Map<String, Object> getLogin(String token, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();

        YsUser wxUserInfo = new YsUser();
        if (wxUserMapper.getUserCount(token) == 0) {
            String name = request.getParameter("name");
            String url = request.getParameter("url");
            wxUserInfo.setOpenid(token);
            wxUserInfo.setUserName(EmojiParser.removeAllEmojis(name));
            wxUserInfo.setUserUrl(url);
            try {


                wxUserMapper.addUser(wxUserInfo);
                wxUserWalletMapper.addWxUserWalletMapper(wxUserInfo);
                //wxUserWalletMapper.addUserCoupon(wxUserInfo);
                //map.put("add", "1");

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //登陆
			wxUserInfo = wxUserMapper.getWxUserInfo(token);
			// 由于老用户可能缺失userName或userUrl字段信息，当发现缺失两者之一时，则获取登录后传入的name和url
			if (StringUtils.isEmpty(wxUserInfo.getUserName()) || StringUtils.isEmpty(wxUserInfo.getUserUrl())) {
				String name = request.getParameter("name");
				String url = request.getParameter("url");
				// 只有两者都不为空（正常情况下，微信登录之后，这两个属性必然不为空），才更新此用户的信息
				if (!StringUtils.isEmpty(url) && !StringUtils.isEmpty(name)) {
                    wxUserInfo.setUserName(EmojiParser.removeAllEmojis(name));
					wxUserInfo.setUserUrl(url);
					wxUserMapper.set(wxUserInfo);
				}
			}
        }
        map.put("wxUserInfo", wxUserInfo);
        map.put("userWallet", wxUserWalletMapper.getUserWallet(wxUserInfo.getId()));
        map.put("userCouponList",wxUserMapper.getUserCouponList(wxUserInfo.getId()));


        return map;
    }

    /**
     * @param token
     * @return
     */
    @RequestMapping("/get_model")
    @ResponseBody
    public Map<String, Object> getModel(String token, String userToken) {
        Map<String, Object> map = new HashMap<String, Object>();
        YsUser wxUserInfo = wxUserMapper.getWxUserInfo(userToken);
        map.put("userWallet", wxUserWalletMapper.getUserWallet(wxUserInfo.getId()));
        WxMoney wxMoney = new WxMoney();
        map.put("wxMoneyList", wxMoneyMapper.findAllList(wxMoney));

        return map;
    }

    /**
     * @return
     */
    @RequestMapping("/add_agents")
    @ResponseBody
    public Map<String, Object> addAgents(String tel, String password) {
        WxAgents wxAgents = new WxAgents();
        wxAgents.setUserName(tel);
        wxAgents.setPassword(password);
        wxAgents.setProportion(new BigDecimal(1));
        Map<String, Object> map = new HashMap<String, Object>();
        if (wxAgentsMapper.getCountTel(tel) == 1) {
            map.put("code", 1);
            map.put("msg", "账户已注册");
            return map;

        } else {
            map.put("code", 0);
            wxAgentsMapper.insert(wxAgents);

        }

        return map;
    }

    /**
     * @return
     */
    @RequestMapping("/get_agents_list")
    @ResponseBody
    public Map<String, Object> addAgents(String id) {
        Map<String, Object> map = new HashMap<String, Object>();

        WxAgentsEquipment wxAgentsEquipment = new WxAgentsEquipment();
        WxAgents wxAgents = new WxAgents();
        wxAgents.setId(id);
        wxAgentsEquipment.setAgents(wxAgents);
        List<WxAgentsEquipment> list = new ArrayList<>();

        list = wxAgentsEquipmentMapper.findList(wxAgentsEquipment);
        map.put("code", 0);
        map.put("data", list);
        map.put("size", list.size());


        return map;
    }
    /** 绑定设备
     * @return
     */
    @RequestMapping("/add_agents_equipment")
    @ResponseBody
    public Map<String, Object> addAgentsEquipment(String id,String number) {
        Map<String, Object> map = new HashMap<String, Object>();
        WxAgents wxAgents=wxAgentsMapper.get(id);
        if(wxAgents.getStatus()==0){
            map.put("code", 1);
            map.put("msg", "分销商审核未通过");
            return map;

        }
        if(wxAgentsEquipmentMapper.getNumberCount(number)!=0){
            map.put("code", 1);
            map.put("msg", number+"设备已被已绑定");
         }else{


            wxAgentsEquipmentMapper.addAgentsEquipment(id,number);

            map.put("code", 0);

        }


        return map;
    }

    /**
     * @return
     */
    @RequestMapping("/set_agents")
    @ResponseBody
    public Map<String, Object> setAgents(String tel, String password, HttpServletRequest request) {
        String address = request.getParameter("address");
        WxAgents wxAgents = new WxAgents();
        wxAgents.setUserName(tel);
        wxAgents.setPassword(password);
        wxAgents.setAddress(address);
        Map<String, Object> map = new HashMap<String, Object>();

        if (wxAgentsMapper.getCountTel(tel) != 1) {
            map.put("code", 1);
            map.put("msg", "账户未注册");
            return map;

        } else {
            wxAgentsMapper.setAgents(tel, null, address);
        }
        map.put("code", 0);
        return map;
    }

    /***
     * 发送注册短信接口
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "sms")
    @ResponseBody
    public Map<String, Object> sms(String tel, int type, HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        if (type == 1) {
            if (wxAgentsMapper.getCountTel(tel) != 1) {
                map.put("code", 1);
                map.put("msg", "账户未注册");
                return map;
            }

        } else {
            if (wxAgentsMapper.getCountTel(tel) == 1) {
                map.put("code", 1);
                map.put("msg", "账户已注册");
                return map;
            }
        }
        Achieve achieve = new Achieve();
        String code = achieve.getVerificationCodeId();
        aliFishSms(SMSURL, SMSKEY, SMSSECRET, code, tel, SMSCODE);
        map.put("code", 0);
        map.put("data", code);

        return map;
    }

    /**
     * 阿里大鱼注册短信
     *
     * @param url    短信请求地址
     *               正式环境 http://gw.api.taobao.com/router/rest
     *               测试环境  http://gw.api.tbsandbox.com/router/rest
     *               APP证书 里的
     * @param key    App Key:
     * @param secret App Secret:
     * @throws ApiException
     */

    public static AlibabaAliqinFcSmsNumSendResponse aliFishSms(String url, String key, String secret, String code, String tel, String smcCode) throws ApiException {
        DefaultTaobaoClient client = new DefaultTaobaoClient(url, key, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setExtend("黄牛在线");
        req.setSmsType("normal");
        req.setSmsFreeSignName("黄牛在线");
        net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
        jsonObject.put("code", code);
        req.setSmsParamString(jsonObject.toString());
        req.setRecNum(tel);
        req.setSmsTemplateCode(smcCode);
        AlibabaAliqinFcSmsNumSendResponse rsp = (AlibabaAliqinFcSmsNumSendResponse) client.execute(req);

        return rsp;

    }

    /**
     * @return
     */
    @RequestMapping("/get_agents")
    @ResponseBody
    public Map<String, Object> getAgents(String tel, String password) {
        Map<String, Object> map = new HashMap<String, Object>();

        WxAgents wxAgents = new WxAgents();
        if (wxAgentsMapper.getCountTel(tel) == 1) {
            wxAgents = wxAgentsMapper.getAgents(tel, password);
            if (wxAgents == null) {
                map.put("code", 1);
                map.put("msg", "密码错误");
                return map;

            } else {
                map.put("code", 0);
                map.put("msg", "ok");
                map.put("data", wxAgents);
                return map;

            }

        } else {

            map.put("code", 1);
            map.put("msg", "账户未注册");
        }
        return map;
    }

    /**
     * @param token
     * @return
     */
    @RequestMapping("/wx_user_coupon")
    @ResponseBody

    public Map<String, Object> wxUserCoupon(String token, String userToken, String number, String equipment) {
        Map<String, Object> map = new HashMap<String, Object>();
        YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);
        WxUserCoupon wxUserCoupon = new WxUserCoupon();
        WxUser user = new WxUser();
        user.setId(wxUserInfo.getId());
        wxUserCoupon.setUser(user);
        String typeId = wxCouponTypeMapper.getEquipment(equipment);
        WxCouponType wxCouponType = wxCouponTypeMapper.get(typeId);
        Integer couponTotal = wxCouponTypeMapper.getCouponTotal(number);
        map.put("text1", "恭喜获得");
        map.put("text2", wxCouponType.getTitle());
        map.put("text3", wxCouponType.getTitle() + "优惠卷已放入我的券包中");
        couponTotal = couponTotal == null ? 5 : 5 - couponTotal;
        couponTotal = couponTotal < 0 ? 0 : couponTotal;
        List<WxUserCoupon> wxUserCouponList=wxUserCouponMapper.findList(wxUserCoupon);
        if(wxUserCouponList!=null&&wxUserCouponList.size()>=3){
            map.put("text4", "用户只能领取3张优惠卷");
            map.put("text3", "");
            map.put("text1", "优惠卷领取上限");

            map.put("code",1);
        }
        if (StringUtils.isEmpty(userToken)) {
            if (couponTotal == 0) {
                map.put("text4", "礼包已发完");
                map.put("text3", "");
                map.put("text1", "礼包已发完");

                map.put("code",1);
            } else {

                map.put("text4", "还剩下" + couponTotal + "个礼包不要浪费");
            }
        }else{
            map.put("text5","邀请好友一起拆礼包!");

        }
        map.put("total", couponTotal);
        map.put("wxCouponType", wxCouponType);
        return map;
    }
    /**
     *
     * @param token
     * @return
     */
    @RequestMapping("/wx_user_coupon_list")
    @ResponseBody

    public Map<String,Object> wxUserCouponList( String token,String userToken ){
        Map<String,Object> map=new HashMap<String, Object>();
        YsUser wxUserInfo=wxUserMapper.getWxUserInfo(userToken);
        WxUserCoupon wxUserCoupon=new WxUserCoupon();
        WxUser user=new WxUser();
        user.setId(wxUserInfo.getId());
        wxUserCoupon.setUser(user);
        map.put("wxUserCoupon",wxUserCouponMapper.findAllList(wxUserCoupon));

        return  map;
    }
/**
     * @param token
     * @return
     */
    @RequestMapping("/add_user_coupon")
    @ResponseBody

    public Map<String, Object> addUserCoupon(String token,  String number, String equipment) {
        Map<String, Object> map = new HashMap<String, Object>();
        YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);
        WxUserCoupon wxUserCoupon = new WxUserCoupon();
        WxUser user = new WxUser();
        user.setId(wxUserInfo.getId());
        wxUserCoupon.setUser(user);
        String typeId = wxCouponTypeMapper.getEquipment(equipment);
        WxCouponType wxCouponType = wxCouponTypeMapper.get(typeId);
        Integer couponTotal = wxCouponTypeMapper.getCouponTotal(number);

        couponTotal = couponTotal == null ? 5 : 5 - couponTotal;
        couponTotal = couponTotal < 0 ? 0 : couponTotal;

        if(couponTotal==0){
            map.put("msg", "优惠卷已领完");
            return map;

        }else{
            List<WxUserCoupon> list=wxUserCouponMapper.findList(wxUserCoupon);
            if(list.size()>=3){
                map.put("msg", "已达到优惠卷上限");

            }else{

            //添加次数
            wxUserCoupon.setWay("来源于分享");
            wxUserCoupon.setCouponType(wxCouponType);
             //wxUserCouponMapper.insert(wxUserCoupon);
             wxCouponTypeMapper.setCouponTotal(number);

            map.put("msg",wxCouponType.getTitle()+ "优惠卷已发放");
            }
            return map;

        }

     }

    /**
     * @return
     */
    @RequestMapping("/set_user")
    @ResponseBody
    public Map<String, Object> setUser(String userName, String userUrl, String userToken) {
        Map<String, Object> map = new HashMap<String, Object>();
        YsUser wxUserInfo = wxUserMapper.getWxUserInfo(userToken);
        wxUserInfo.setUserName(userName);
        wxUserInfo.setUserUrl(userUrl);
        wxUserMapper.set(wxUserInfo);
        map.put("userWallet", wxUserWalletMapper.getUserWallet(wxUserInfo.getId()));

        return map;
    }

    /**
     * @return
     */
    @RequestMapping("/getWalletDetails")
    @ResponseBody
    public Map<String, Object> getWalletDetails(String token, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        WxUser wxUserInfo = wxUserMapper.findUniqueByProperty("openid",token);
        if(wxUserInfo!=null){
            WxUserWalletDetails wxUserWalletDetails = new WxUserWalletDetails();
            wxUserWalletDetails.setUser(wxUserInfo);
            Page<WxUserWalletDetails> list = wxUserWalletDetailsService.findPage(new Page<WxUserWalletDetails>(request, response),wxUserWalletDetails);
            map.put("walletDetails", list.getList());
        }else{
            map.put("walletDetails", new ArrayList<>());
        }
        return map;
    }

    /***
     * 上传图片
     *
     * @param path 图片
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/file")
    @ResponseBody
    public Message<Object> set(@RequestParam("filePath") MultipartFile path) throws Exception {

        Business business = new Business();
        List<String> str = FileBean.addPostsUrl(new MultipartFile[]{path}, Global.getConfig("FILE"));
        return business.returnGetMessage(Global.getConfig("url") + "/image/" + str.get(0), 0);
    }

    /**
     * @return 获得玩家小程序openid
     */
    @RequestMapping("/get_openId")
    @ResponseBody
    public Map<String, Object> get_openId(String js_code) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", JSONObject.fromObject(MoneyTest.
                sendGet("https://api.weixin.qq.com/sns/jscode2session?appid="+appid+
                        "&secret="+appsecret+
                        "&js_code=" + js_code +
                        "&grant_type=authorization_code")));
        return map;
    }

    /**
     * 获得小程序openid
     * @param js_code js_code
     * @param type 类型 1-业务员小程序 2-玩家小程序
     * @return
     */
    @RequestMapping("/getOpenId")
    @ResponseBody
    public Map<String, Object> getOpenId(String js_code, Integer type) {
        Map<String, Object> map = new HashMap<String, Object>();

        String appid = "";
        String appsecret = "";
        switch (type) {
            case 1: //业务员小程序
                appid = this.salesmanAppId;
                appsecret = this.salesmanAppSecret;
                break;
            case 2:
            default:
                appid = this.appid;
                appsecret = this.appsecret;
                break;
        }

        map.put("data", JSONObject.fromObject(MoneyTest.
                sendGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                        "&secret=" + appsecret +
                        "&js_code=" + js_code +
                        "&grant_type=authorization_code")));
        return map;
    }

    /**
     * @return
     */
    @RequestMapping("/get_code")
    @ResponseBody
    public Map<String, Object> get_code(String ACCESS_TOKEN) {
        Map<String, Object> map = new HashMap<String, Object>();

//        map.put("data",  JSONObject.fromObject(MoneyTest.
//                sendGet("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ACCESS_TOKEN +
//                        "&secret="+secret +
//                        "&js_code=" +js_code+
//                        "&grant_type=authorization_code")));
        return map;
    }
}
